// pages/pallet_details/pallet_details.js
var app = getApp();
var util = require('../../util.js');
var boxNumTempArr = [];   // 临时保存箱号输入信息的数组



Page({

  /**
   * 页面的初始数据
   */
  data: {
    data: {},              // 订单详情数据
    orderinfo: null,
    time: '00:00',
    date:'2018-01-01',
    goodsImg: '',          // 提货照片路径
    boxNum: [],            // 箱号的值 是一个数组 保存着每一个货号input 输入框的值
    unloadGoodsImg: '',    // 卸货照片的路径
    returnCabinetImg: '',  // 保存还柜照片的路径
    feeList: [],           // 需要缴纳费用的列表 
	feeList_index: 0,
	costValue: '',
    feeValue: []           // 保存费用输入框的值
  },

  call: function (res) {
    wx.makePhoneCall({
      phoneNumber: res.currentTarget.dataset.num //仅为示例，并非真实的电话号码
    })
  },

  bindCostChange: function (e) {
	  console.log('picker发送选择改变，携带值为', e.detail.value);
	  this.setData({
		  feeList_index: e.detail.value,
	  })
  },

  bindDateChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      date: e.detail.value
    })
  },
  bindTimeChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      time: e.detail.value
    })
  },
  // 获取订单详情
  getOrderInfo: function(res){
    var that = this;
    app.getLoginSession(function (session) {
      wx.request({
        url: app.api + '/wx_log_test/order/' + that.data.orderId,
        data:{
          token: session,
        },
        success: function (res) {
          if(res.statusCode == 200){
            if (res.data.msg == 'OK'){
              console.log(res.data.data);

              that.setData({
				  data: that.changestatus(res.data.data)
              })


              // 如果当前为还柜状态 获取需要缴纳的费用名称 
              if (res.data.data.order.cabinetUnloadPic && res.data.data.order.unit != '吨') {

                app.getLoginSession(function(session) {
                  wx.request({
                    url: app.api + '/wx_log_test/sys/feename',
                    data: {
                      token: session
                    },
                    success: function (res) { 
                      that.setData({
                        feeList: res.data.data
                      })
                    
                    },
                    fail: function () {
                      self.tips('抱歉，网络出错请稍后重试');
                     }
                  })
                });
                
              }
              
              
              var amount = that.data.data.order.goodWeight;

              // 初始化箱号数组
              // 后台有数据就保存 没有就存null
              var boxNum1 = that.data.data.order.cabinetP1 || null;
              var boxNum2 = that.data.data.order.cabinetP2 || null;


              boxNumTempArr = [boxNum1, boxNum2];

              console.log(boxNumTempArr);

              // 保存箱号input 在input 事件中 value 的数组
              // 初始化货柜箱图片url

              that.setData({
                boxNum: boxNumTempArr,
                goodsImg: res.data.data.order.cabinetPic
              })



              that.data.data.order.sendstop ? that.data.data.order.sendstop = util.formatDate(new Date((parseInt(that.data.data.cargo.sendDate2) / 1000 + 691200) * 1000), 'YYYY-MM-dd hh:mm:ss') : that.data.data.order.sendstop = '';


              that.data.data.order.deliverysend ? that.data.data.order.deliverysend = util.formatDate(new Date((parseInt(that.data.data.order.loadOn) / 1000 + 691200) * 1000), 'YYYY-MM-dd hh:mm:ss') : that.data.data.order.deliverysend = '';


              that.data.data.cargo.sendDate1 ? that.data.data.cargo.sendDate1 = util.formatDate(new Date(that.data.data.cargo.sendDate1), 'YYYY-MM-dd hh:mm:ss') : that.data.data.cargo.sendDate1 = '';


              that.data.data.cargo.sendDate2 ? that.data.data.cargo.sendDate2 = util.formatDate(new Date(that.data.data.cargo.sendDate2), 'YYYY-MM-dd hh:mm:ss') : that.data.data.cargo.sendDate2 = '';


              that.data.data.order.deliveryOn ? that.data.data.order.deliveryOn = util.formatDate(new Date(that.data.data.order.deliveryOn), 'YYYY-MM-dd hh:mm:ss') : that.data.data.order.deliveryOn = '';


              that.data.data.order.unloadOn = that.data.data.order.unloadOn ? util.formatDate(new Date(that.data.data.order.unloadOn), 'YYYY-MM-dd hh:mm:ss') : null;
              that.data.data.order.loadOn = that.data.data.order.loadOn ? util.formatDate(new Date(that.data.data.order.loadOn), 'YYYY-MM-dd hh:mm:ss') : null;
              that.data.data.order.cabinetReturnDate = that.data.data.order.cabinetReturnDate ? util.formatDate(new Date(that.data.data.order.cabinetReturnDate), 'YYYY-MM-dd hh:mm:ss') : null;


              that.setData({
                data: that.data.data
              })

              console.log('data.order.sendstop');
              // console.log(res.data.data.order.deliverysend);
              console.log(that.data.data.cargo.sendstop);


            }else{
              wx.showModal({
                title: '提示',
                content: res.data.msg,
              })
            }
          }else{
            wx.showModal({
              title: '提示',
              content: '接口请求错误：错误码：' + res.statusCode
            })
          }
        }
      })
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    this.setData({
      options:options
    })
    if (options.id){
      this.setData({
        orderId: options.id
      })

      // 初始化订单信息
      this.getOrderInfo();
    }else{
      wx.showModal({
        title: '提示',
        content: '订单号不能为空',
      })
    }
  },



  //更改状态
  changestatus(list) {
    if (list.order.loadWeight != 0 && list.order.unloadWeight == 0) {
      list.status = 5;//运输中-->已送达 待卸货状态
    } else if (list.status == 7 && list.order.loadWeight == 0) {
      list.status = 3;//待提货-->提货完成
    } else if (list.status == 7 && list.order.unloadWeight != 0 && list.order.loadWeight != 0 && list.order.position == null) {
      list.status = 6;//等待入库-->入库卸货
    } else if (list.status == 1) {
      list.status = 1;//待接单-->取消派单
    } else if (list.status == 3 && list.order.loadWeight != 0 && list.order.unloadWeight == 0) {
      list.status = 5;//已超时,运输中
    } else if (list.status == 3 && list.order.loadWeigh == 0) {
      list.status = 3;//已超时，待提货-->提货完成
    } else if (list.status == 3 && list.order.unloadWeight != 0 && list.order.loadWeight != 0 && list.order.position == null) {
      list.status = 6;//已超时，等待入库-->入库卸货
    } else if (list.status == 8) {
      list.status = 4;//已完成-->取消派单
    }
    return list
  },
  //输入接单重量
  input:function(res){
    var that = this;
    that.data.data.order.goodWeight=res.detail.value;
    that.data.data.cargo.remain = that.data.data.cargo.remain == null ? that.data.data.cargo.gross : that.data.data.cargo.remain
    that.setData({
      data:that.data.data,
    })
  },
  //确认接单
  suerorder:function(res){
    var that = this;
    var time = that.data.date + ' ' + that.data.time;
    console.log(time);
    time = Date.parse(new Date(time));
    var startTime = Date.parse(new Date(that.data.data.cargo.sendDate1));
    var endTime = Date.parse(new Date(that.data.data.cargo.sendDate2));
    if (time < startTime || time > endTime) {
      wx.showModal({
        title: '提示',
        content: '您选择时间不在范围内',
      })
    } else if (!/^\d+(\.\d+)?$/.test(that.data.data.order.goodWeight) || that.data.data.order.goodWeight>that.data.data.cargo.remain){
      wx.showModal({
        title: '提示',
        content: '请输入正确的接单重量！',
      })
    }else{
      app.getLoginSession(function (session) {
        wx.request({
          url: app.api + '/wx_log_test/order/update?token=' + session,
          data: {
            loadOn:null,
            loadPicUrl:null,
            loadWeight:0,
            orderId: that.data.options.id,
            position:null,
            prePosition:null,
            suspensionInfo: "string",
            unLoadPicUrl:null,
            unloadOn:null,
            unloadWeight:0,
            deliveryOn:time,
            goodWeight: that.data.data.order.goodWeight,
          },
          method: 'POST',
          success: function (res) {
            var res = res.data;
            if (res.msg == "OK") {
              wx.showToast({
                title: '接单成功！！！',
                icon: 'success',
                success: function (res) {
                  wx.navigateBack({
                    delta: 1
                  })
                }
              })
            } else {
              wx.showToast({
                title: '请重试！',
                icon: 'loading',
              })
            }
          },
          fail: function (res) {
            wx.showToast({
              title: '请重试！',
              icon: 'loading'
            })
          }
        })
      })
    }
  },
  //取消接单
  closeorder:function(res){
    var that = this;
    app.getLoginSession(function (session) {
      wx.request({
        url: app.api+'/wx_log_test/order/unappoint?token='+session+'&&orderid='+that.data.data.order.id,
        method:'POST',
        success:function(res){
          var res = res.data;
          console.log(res);
          if(res.data==true){
            wx.showModal({
              title: '温馨提示',
              content: '取消接单成功！',
              showCancel:false,
              success: function (res) {
                if (res.confirm) {
                  wx.navigateBack({
                    delta:1
                  })
                }
              }
            })
          }else{
            wx.showToast({
              title: '失败，请重试！',
              icon:'loading'
            })
          }
        },fail:function(res){
          wx.showToast({
            title: '失败，请重试！',
            icon: 'loading'
          })
        }
      })
    })
  },


  /** 箱号输入框输入事件 */
  boxNumInput(e) {
    boxNumTempArr[e.target.id] = e.detail.value;
    this.setData({
      boxNum: boxNumTempArr
    })
    console.log(this.data.boxNum);
  },


  // 提示框
  tips: function (txt) {
    wx.showModal({
      title: '提示',
      content: txt,
      showCancel: false
    })
  },

  /** 上传照片 **/
  uploadImg: function (img, name) {
	  var that = this;
	  var imgs = that.data.imgs;
	  wx.uploadFile({
		  url: app.api + '/wx_log_test/image/upload',
		  filePath: img,
		  name: 'file',
		  method: 'POST',
		  header: {
			  'content-type': 'multipart/form-data'
		  },
		  success: function (res) {
			  console.log(res);
			  var data = JSON.parse(res.data);
			  var rlt = data.data;
			  if (data.statusCode = 200) {
				  console.log('图片上传成功' + rlt);
				  console.log(name);
				  that.setData({
					  [name]: rlt
				  })
			  }
			  else {
				  console.log(data);
				  wx.showToast({
					  title: '图片上传失败',
					  icon: 'none',
				  });
				  return ;
			  }
		  },
		  fail: function () {
			  console.log("失败");
			  return;
		  }
	  })
  },

  /** 选择订单照片 */
  chooseImg(e) {
    var self = this;
    wx.chooseImage({
      count: 1,
      success: function (res) {
        console.log(res);
        
        // 如果当前为上传提货图片设置goodsImg 的数据
        if (e.target.dataset.type == 'goodsWeight') {
			//上传图片
			self.uploadImg(res.tempFilePaths[0], 'goodsImg')
        }


        // 如果当前为上传卸货图片设置unloadGoodsImg 的数据
        if(e.target.dataset.type == 'unload') {
			//上传图片
		   self.uploadImg(res.tempFilePaths[0], 'unloadGoodsImg')
        }


        // 如果是上传还柜照片设置 returnCabinetImg 的数据
        if (e.target.dataset.type == 'returnCabinet') {
			//上传图片
			self.uploadImg(res.tempFilePaths[0], 'returnCabinetImg')
        }
        
      },
      fail: function () {
        self.tips('选取图片失败');
      }
    })
  },


  /** 
   *  确认提货按钮点击事件
   *  确认卸货按钮点击事件
   */
  confirm(e) {
    var self = this;

    var imgSrc = '';        // 对应的保存图片路径页面属性
    var requestUrl = '';    // 对应的请求地址

    if(e.target.dataset.type == 'carryGoods') {
      // 如果是提货按钮点击
      imgSrc = this.data.goodsImg;
      // 设置提货请求地址
      requestUrl = app.api + '/wx_log_test/cabinet/pick';
    }

    if (e.target.dataset.type == 'unloadGoods') {
      // 如果是卸货按钮点击
      imgSrc = this.data.unloadGoodsImg;
      // 设置提货请求地址
      requestUrl = app.api + '/wx_log_test/cabinet/do';
    }




    // 检测箱号
    // 因为第二个箱号为选填 所以只检测第一个箱号是否合法即可
    if (!this.data.boxNum[0]) {
      this.tips('你还有未填写的箱号');
      console.log(this.data.boxNum);
      console.log(!this.data.boxNum[0]);
      return;
    }


    if(!imgSrc) {
      this.tips('请上传货柜照片');
      return;
    }


    // 填写正确发送请求
    // 请求的数据
    var requestParams = {};


    // 首先填入箱号数据
    for (var i = 0; i < this.data.boxNum.length; i++) {
      requestParams['cabinet' + (i + 1)] = this.data.boxNum[i];
    }

    // 填入货柜图片url
    requestParams['cabinetPic'] = this.data.goodsImg;


    //填入orderId
    requestParams['orderId'] = this.data.data.order.id;



    // 填入token
    app.getLoginSession(function(session) {
      requestParams['token'] = session;
      
      console.log(requestParams);
      console.log(requestUrl);

      
      
      wx.request({
        url: requestUrl,
        method: 'POST',
        data: requestParams,
        success(res) {
          // 请求成功后回到订单列表页
          if(res.data.msg == 'OK') {
            wx.redirectTo({
              url: '/pages/order/order'
            })
          }else {
            self.tips('服务器出了小问题 请稍后重试');
            wx.redirectTo({
              url: '/pages/order/order'
            })
          }
          
        },
        fail() {
          self.tips('抱歉网络出错，请稍后重试');
        }
      })


    });

  },

/** 费用价格 */
costInput(e){
	var value = e.detail.value;
	this.setData({
		costValue: value,
	})
},

  /**添加费用 */
  addCost(e) {
	var that = this;
    var feeName = e.currentTarget.dataset.feename;
	var feeValue = that.data.feeValue;
	var costValue = that.data.costValue;
	console.log(costValue);
	if (costValue != '' && !isNaN(costValue)){    //判断是否有输入费用
		if (feeValue.length>0){
			for (var x in feeValue) {
				if (feeValue[x].feeName == feeName) {
					console.log('aaa');
					wx.showModal({
						title: '提示',
						content: '该费用已添加',
						showCancel: false,
					});
					break;
				}
				else {
					console.log('ddd');
					var item = {
						feeName: feeName,
						total: costValue
					}
					feeValue.push(item);
					break;
				}
			}
		}
		else{
			var item = {
				feeName: feeName,
				total: costValue
			}
			feeValue.push(item);
		}
	}
	else{
		wx.showModal({
			title: '提示',
			content: '请输入该费用总价（数字）',
			showCancel: false,
		});
	}

    // 设置feeValue 的值
	that.setData({
		feeValue: feeValue
    });

	console.log(that.data.feeValue);
    
  },

  /** 删除费用**/
  deleteCost(e){
	  var index = e.currentTarget.dataset.index;
	  var feeValue = this.data.feeValue;
	  console.log(index);
	  feeValue.splice(index);
	  this.setData({
		  feeValue : feeValue,
	  })
  },


  /**
   * 确认还柜按钮点击事件
   * 
  */
  confirmReturnCabinet() {
    var self = this;


    // 检测是否填写了箱号
    // 同理 只检测第一个箱号是否输入了值
    if (!this.data.boxNum[0]) {
      this.tips('你还有未填写的箱号');
      console.log(this.data.boxNum);
      return;
    }



    // 检测是否有还柜图片
    if (!this.data.returnCabinetImg) {
      this.tips('请上传还柜图片');
      return;
    }


    // 检测是否已经填写了还柜费用
    for (var i = 0; i < this.data.feeValue.length; i++) {
      if (!this.data.feeValue[i] || !this.data.feeValue[i].total) {
        console.log(this.data.feeValue);
        this.tips('请输入还柜费用');
        return;
      }
    }


    // 组装请求数据
    var requestParams = {};


    // 录入费用数组
    requestParams.billVos = this.data.feeValue;




    // 录入柜号
    console.log(this.data.boxNum);
    for(var j = 0; j < this.data.boxNum.length; j++){
      requestParams['cabinet' + (j + 1)] = this.data.boxNum[j];
    }


    // 录入还柜图片路径
    requestParams.cabinetPic = this.data.returnCabinetImg;


    // 录入订单号
    requestParams.orderId = this.data.data.order.id;


    // 录入token
    app.getLoginSession(function(session) {
      requestParams.token = session;

      
      wx.request({
        url: app.api + '/wx_log_test/cabinet/do',
        data: requestParams,
        method: 'POST',
        success: function(res) {
          if(res.data.msg == 'OK') {
            wx.redirectTo({
              url: '/pages/order/order'
            })
          }else {
            self.tips('服务器有点小问题，请稍后重试');
          }
        },
        fail: function(res) {
          self.tips('抱歉网络出错，请稍后重试');
        }
      })
      
      
      console.log(requestParams);
    })

  }
})